/*请求域名管理*/
export const baseURL='http://10.12.9.219'
/*图片路劲拼接*/
export const imgPath='http://10.12.9.219/src/'
// 时间戳转换日期格式
function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}
export const formatDate = (date, fmt) => {
  if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
};
// 检查是否有新版本
export const Version = (curV,reqV) => {
	var arr1=curV.split('.'); //服务器版本号
	var arr2=reqV.split('.'); //本地版本号
	//将两个版本号拆成数字
	var minL= Math.min(arr1.length,arr2.length);
	var pos=0;        //当前比较位
	var diff=0;        //当前为位比较是否相等
	//逐个比较如果当前位相等则继续比较下一位
	while(pos<minL){
		diff=parseInt(arr1[pos])-parseInt(arr2[pos]);
		if(diff!=0){
			break;
		}
		pos++;
	}
	if (diff>0) {
		return '有新版本'
	}else if (diff==0) {
		return '稳定版'
	}else{
		return '服务版本过低'
	}
}
// 下载wgt包
export const downloaderWgt = (wgtUrl) => {
	plus.nativeUI.showWaiting("正在下载应用更新文件...");
	plus.downloader.createDownload( wgtUrl, {filename:"_doc/update/"}, function(d,status){
	    if ( status == 200 ) {
	        console.log("下载wgt成功："+d.filename);
	        installWgt(d.filename); // 安装wgt包  
	    } else {  
	        console.log("下载wgt失败！");
	        plus.nativeUI.alert("应用更新文件下载失败");
	    }  
	    plus.nativeUI.closeWaiting();
	}).start();
}
// 安装WGT包
export const installWgt = (path) => {
	plus.nativeUI.showWaiting("正在安装应用更新文件...");  
	plus.runtime.install(path,{force:true},function(){  
	    plus.nativeUI.closeWaiting();  
	    console.log("安装wgt文件成功！");  
	    plus.nativeUI.alert("应用资源更新完成！",function(){  
	        plus.runtime.restart();  
	    });  
	},function(e){  
	    plus.nativeUI.closeWaiting();  
	    console.log("安装wgt文件失败["+e.code+"]："+e.message);  
	    plus.nativeUI.alert("更新应用安装失败！");  
	}); 
}
// 控制是否显示消息红点
export const setTitleNViewStyle = (index, show) => {
	let pages = getCurrentPages();  
	let page = pages[pages.length - 1];  
	// #ifdef APP-PLUS  
	let currentWebview = page.$getAppWebview();  
	if(show){  
		if(index === 0){  
			currentWebview.showTitleNViewButtonRedDot({index:index})  
		}else{  
			currentWebview.setTitleNViewButtonBadge({index:index})  
		}  
	}else{  
		if(index === 0){  
			currentWebview.hideTitleNViewButtonRedDot({index:index})  
		}else{  
			currentWebview.removeTitleNViewButtonBadge({index:index})  
		}  
	}  
	// #endif  

	// #ifdef H5  
	if(show){  
		if(index === 0){  
			document.querySelectorAll('.uni-page-head-hd .uni-page-head-btn')[1].classList.add('uni-page-head-btn-red-dot');  
		} else {  
			document.querySelector('.uni-page-head-ft .uni-page-head-btn').classList.add('uni-page-head-btn-red-dot');  
		}  
	} else {  
		if(index === 0){  
			document.querySelector('.uni-page-head-btn-red-dot').classList.remove('uni-page-head-btn-red-dot');  
		} else {  
			document.querySelector('.uni-page-head-ft .uni-page-head-btn-red-dot').classList.remove('uni-page-head-btn-red-dot');  
		}  
	}  
	// #endif 
}

function getDataColumn(main, uri, selection, selectionArgs) {
		plus.android.importClass(main.getContentResolver());
		let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs,
		null);
		plus.android.importClass(cursor);
		if(cursor != null && cursor.moveToFirst()) {
		var column_index = cursor.getColumnIndexOrThrow('_data');
		var result = cursor.getString(column_index)
		cursor.close();
		return result;
		}
		return null;
}
export const chooseFile = (callback, acceptType) => {
//acceptType为你要查的文件类型"image/*"，"audio/*"，"video/*;image/*"  
	// intent.setType("image/*");
	//intent.setType("audio/*"); 
	//选择音频
	//intent.setType("video/*;image/*"); 
	//选择视频 （mp4 3gp 是android支持的视频格式）
	var CODE_REQUEST = 1000;
	var main = plus.android.runtimeMainActivity();
	if(plus.os.name == 'Android') {
			var Intent = plus.android.importClass('android.content.Intent');
			var intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			if(acceptType) {
					intent.setType(acceptType);
			} else {
					intent.setType("*/*");
			}
			main.onActivityResult = function(requestCode, resultCode, data) {
					if(requestCode == CODE_REQUEST) {
							var uri = data.getData();
							plus.android.importClass(uri);
							var Build = plus.android.importClass('android.os.Build');
							var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

							var DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
							// DocumentProvider
							if(isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
											console.log("版本大于 4.4 ");
									// ExternalStorageProvider
									if("com.android.externalstorage.documents" == uri.getAuthority()) {
											var docId = DocumentsContract.getDocumentId(uri);
											var split = docId.split(":");
											var type = split[0];

											if("primary" == type) {
													var Environment = plus.android.importClass('android.os.Environment');
													callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
											} else {
													var System = plus.android.importClass('java.lang.System');
													var sdPath = System.getenv("SECONDARY_STORAGE");
													if(sdPath) {
															callback(sdPath + "/" + split[1]);
													}
											}
									}
									// DownloadsProvider
									else if("com.android.providers.downloads.documents" == uri.getAuthority()) {
											var id = DocumentsContract.getDocumentId(uri);
											var ContentUris = plus.android.importClass('android.content.ContentUris');
											var contentUri = ContentUris.withAppendedId(
											//    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
											Uri.parse("content://downloads/public_downloads"), id);
											callback(getDataColumn(main, contentUri, null, null));
									}
									// MediaProvider
									else if("com.android.providers.media.documents" == uri.getAuthority()) {
											var docId = DocumentsContract.getDocumentId(uri);
											var split = docId.split(":");
											var type = split[0];

											var MediaStore = plus.android.importClass('android.provider.MediaStore');
											if("image" == type) {
											contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
											} else if("video" == type) {
											contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
											} else if("audio" == type) {
											contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
											}

											var selection = "_id=?";
											var selectionArgs = new Array();
											selectionArgs[0] = split[1];

											callback(getDataColumn(main, contentUri, selection, selectionArgs));
									}
							}
							// MediaStore (and general)
							else if("content" == uri.getScheme()) {
									callback(getDataColumn(main, uri, null, null));
							}
							// File
							else if("file" == uri.getScheme()) {
									callback(uri.getPath());
							}
					}
			}
			main.startActivityForResult(intent, CODE_REQUEST);
	}
}
